<template>
    <div>
        <el-dialog v-model="props.dialogVisible" :title="newTitle" draggable width="800"
            :before-close="handleServiceClose">
            <el-form :inline="true" :model="submitFrom" label-width="auto" ref="siteDomainRef" :rules="rules"
                label-position="left">
                <el-form-item label="服务商" prop="providerId" style="width: 100%" required>
                    <el-select v-model="submitFrom.providerId" placeholder="请选择" @change="changeProvider">
                        <el-option v-for="dict in sys_provider" :key="dict.value" :label="dict.name"
                            :value="dict.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="服务商账号" style="width: 100%" prop="serverId" required>
                    <el-select v-model="submitFrom.serverId" placeholder="请选择">
                        <el-option v-for="dict in sys_account" :key="dict.value" :label="dict.username"
                            :value="dict.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="域名" style="width: 100%" prop="domainName" required>
                    <el-input v-model.trim="submitFrom.domainName" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="开始时间" style="width: 100%" required prop="newInitiate">
                    <el-date-picker v-model="submitFrom.newInitiate" type="datetime" placeholder="请选择"
                        style="width: 100%" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                        time-format="A hh:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" @change="initiateTime" />
                </el-form-item>
                <el-form-item label="到期时间" style="width: 100%" required prop="newExpire">
                    <el-date-picker v-model="submitFrom.newExpire" placeholder="请选择" style="width: 100%" type="datetime"
                        format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss" :disabled-date="pickerOptions" />
                </el-form-item>
                <el-form-item label="当前状态" style="width: 100%" prop="status" required>
                    <el-select v-model="submitFrom.status" placeholder="请选择">
                        <el-option v-for="dict in sys_site_status" :key="dict.id" :label="dict.name"
                            :value="dict.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="备注" style="width: 100%" prop="remark">
                    <el-input maxlength="300" show-word-limit type="textarea" placeholder="请输入" :rows="7" resize="none"
                        v-model.trim="submitFrom.remark"></el-input>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleServiceClose">取消</el-button>
                    <el-button type="primary" @click="handleServiceSure(siteDomainRef)">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, onMounted, watch, reactive } from "vue";
const emits = defineEmits(["handleServiceClose", "handleServiceSure"]);
const { proxy } = getCurrentInstance();
const newTitle = ref("新增"); //名称
const siteDomainRef = ref(null);
const sys_provider = ref([]); //服务商
const sys_account = ref([]); //服务商账号
const submitFrom = ref({
    providerId: null, //服务商
    serverId: null, //服务商账号
    domainName: '',//用户名
    startTime: null, //开始时间
    endTime: null, //到期时间
    status: 1, //状态
    remark: "", //备注信息

    newInitiate: "",
    newExpire: "",
}); //参数

const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false,
    },
    // 传值数据对象
    publicItem: {
        type: Object,
        default: {},
    },
});
onMounted(() => {
    getSet();
});
watch(
    () => props.dialogVisible,
    () => {
        if (!props.dialogVisible) return;
        if (Object.keys(props.publicItem).length) {
            newTitle.value = "编辑";
            getDetails(props.publicItem); //获取详情
        } else {
            newTitle.value = "新增";
            submitFrom.value.newInitiate = proxy.getCurrent();
        }
    }
);
// 确定事件
const handleServiceSure = (formEl) => {
    if (!formEl) return;
    formEl.validate((valid, fields) => {
        if (valid) {
            submitFrom.value.startTime = proxy.convertTime(
                1,
                submitFrom.value.newInitiate
            );
            submitFrom.value.endTime = proxy.convertTime(
                1,
                submitFrom.value.newExpire
            );
            if (newTitle.value === "新增") {
                site.general
                    .sitedomainAdd({
                        data: submitFrom.value,
                    })
                    .then((res) => {
                        if (res.code === 200) {
                            emits("handleServiceSure");
                            proxy.resetForm("siteDomainRef");
                            proxy.$modal.msgSuccess(`新增成功`);
                        }
                    });
            } else {
                site.general
                    .sitedomainUpdatebyid({
                        pathParams: {
                            id: props.publicItem.id,
                        },
                        data: submitFrom.value,
                    })
                    .then((res) => {
                        if (res.code === 200) {
                            emits("handleServiceSure");
                            proxy.resetForm("siteDomainRef");
                            proxy.$modal.msgSuccess(`修改成功`);
                        }
                    });
            }
        }
    });
};
// 取消事件
const handleServiceClose = () => {
    proxy.resetForm("siteDomainRef");
    emits("handleServiceClose");
};

const getSet = () => {
    let from = {
        pageNum: 1,
        pageSize: 999,
        param: {}

    };
    // 服务商
    site.general
        .siteserverproviderList({
            data: from,
        })
        .then((res) => {
            sys_provider.value = res.data;
            // console.log( sys_provider.value,'服务商');
        });
};

const addLevelToTree = (tree, parentLevel = 0) => {
    return tree.map((item) => ({
        ...item,
        newId: `${item.id}-${parentLevel + 1}`,
        children: item.children
            ? addLevelToTree(item.children, parentLevel + 1)
            : undefined,
    })
    )
}
const getDetails = (item) => {
    // site.general.sitedomainGetbyid({
    site.general
        .sitedomainGetbyid({
            pathParams: {
                id: item.id,
            },
        })
        .then((res) => {
            submitFrom.value.providerId = res.data.providerId;
            submitFrom.value.serverId = res.data.serverId;
            submitFrom.value.domainName = res.data.domainName;

            submitFrom.value.newInitiate = proxy.DateTime(res.data.startTime);
            submitFrom.value.newExpire = proxy.DateTime(res.data.endTime);
            submitFrom.value.remark = res.data.remark;
            submitFrom.value.status = res.data.status;
            getAccount(res.data.providerId);
        });
};

const getAccount = (id) => {
    let from = {
        pageNum: 1,
        pageSize: 999,
        param: {
            providerId: id,
        },
    };
    site.general
        .sitecloudserverList({
            data: from,
        })
        .then((res) => {
            sys_account.value = res.data;
            // console.log(sys_account.value ,'账号');
        });
}
var defaultProps = reactive({
    children: "children",
    label: "description",
    value: "id", // 指定 id 作为 value 属性
});
// 选择服务商调取服务商账号
const changeProvider = (id) => {
    submitFrom.value.serverId = null;
    getAccount(id)
};

// 开始时间选择事件
const initiateTime = (data) => {
    console.log(data);
    // 开始时间>到期时间
    if (!submitFrom.value.newExpire) return
    if (proxy.convertTime(1, data) > proxy.convertTime(1, submitFrom.value.newExpire)) return submitFrom.value.newExpire = ''//到期时间滞空
}
const pickerOptions = (data) => {
    let initiate = new Date(submitFrom.value.newInitiate).getTime();
    let newDate = new Date(data).getTime();
    return initiate > newDate
}

const rules = reactive({
    providerId: [
        { required: true, message: "请选择", trigger: "blur" },
    ],
    serverId: [{ required: true, message: "请选择", trigger: "blur" }],
    newInitiate: [{ required: true, message: "请选择", trigger: "blur" }],
    newExpire: [{ required: true, message: "请选择", trigger: "blur" }],
    domainName: [{ required: true, message: "请输入", trigger: "blur" }, {
        pattern: /(?!.*--)(?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.[a-zA-Z]{2,6}$/,
        message: "请输入正确的域名",
        trigger: "blur",
    }],
});
const sys_site_status = ref([
    {
        name: "正常",
        id: 1,
    },
    {
        name: "停用",
        id: 0,
    },
]); //站点状态
</script>